<?php

namespace app\miniprograms\controller;

use controller\BasicAdmin;
use service\DataService;
use service\NodeService;
use service\ToolsService;
use think\App;;
use think\Db;
use think\Exception;

/**
 * Class Area
 * @package app\admin\controller
 * @author liuda <1576283429@qq.com>

 * @date
 */
class Cart extends BasicAdmin
{
    public $table = 'cart';

    public function index(){

        $this->title = '学生卡管理';
        $cart_no = $this->request->get('cart_no');
        if(!empty($cart_no)){
            $where = " cart_no = '$cart_no' ";
            $data = Db::table('cart')->where($where)->select();
            $this->assign('list', $data);
            return $this->fetch();
        }else{
            return parent::_list(Db::table('cart')->field('*')->order('id desc'));
        }
    }

    /**
     * 添加地区
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function add()
    {
        return $this->_form($this->table, 'form');
    }


    /**
     * 表单数据默认处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _form_filter(&$data)
    {
        if ($this->request->isPost()) {
            $id =  $this->request->post('id');
            $data['cart_no'] = $this->request->post('cart_no');
            $data['create_time'] = time();
            if(empty($id)){
                try{
                    Db::name('cart')->insert($data);
                    $this->success('恭喜, 数据保存成功!', '');
                }catch (Exception $e){
                    $this->error('添加数据失败，请稍后再试！');
                }
            }else{
                try{
                    Db::name('cart')->where('id',$id)->update($data);
                    $this->success('恭喜, 数据保存成功!', '');
                }catch (Exception $e){
                    $this->error('添加数据失败，请稍后再试！');
                }
            }
        }
    }


    /*
     * 编辑
     */
    public function edit()
    {
        $id =  $this->request->get('id');
        $list = Db::table('cart')->where(['id'=>$id])->find();
        $this->assign('list', $list);
        return $this->_form($this->table, 'form');
    }


    /**
     * 删除
     */
    public function del(){
        $id =  $this->request->get('id');
        try{
            Db::table('cart')->where(['id'=>$id])->delete();
            $this->success('删除成功!', '');
        }catch (Exception $e){
            $this->error('删除失败，请稍后再试！');
        }
    }


    public function cartActive(){
        $this->title = '学生卡赠送管理';
        return parent::_list(Db::table('card_gift')->field('*')->order('id desc'));
    }

    public function editActive(){
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $gift_amount = ($this->request->post('gift_amount'))*100;
            $max_count = ($this->request->post('max_count'));
            try{
                Db::name('card_gift')->where('id',$id)->update(['gift_amount'=>$gift_amount,'max_count'=>$max_count]);
                $this->success('恭喜, 数据保存成功!', '');
            }catch (Exception $e){
                $this->error($e->getMessage());
            }

        }else{
            $id =  $this->request->get('id');
            $list = Db::table('card_gift')->where('id',$id)->find();
            $this->assign('list', $list);
            return $this->_form($this->table, 'formactive');
        }
    }


    public function upload(){
        if ($this->request->isPost()) {
            if($this->getExt($_FILES["uploadfile"]["name"]) !='csv'){
                return json_encode(['code'=>false,'msg'=>'请上传csv文件'], JSON_UNESCAPED_UNICODE);
            };
            $csvList = $this->ReadCsv($_FILES["uploadfile"]["tmp_name"]);
           foreach ($csvList as $k =>$v){
               if(empty($v)){
                   continue;
               }
               $isExit = Db::table('cart')->where('cart_no',$v)->count();
               if(!$isExit){
                   $insertData = [
                       'cart_no' => $v,
                       'create_time' => time()
                   ];
                   Db::name('cart')->insert($insertData);
               }
           }
            return json_encode(['code'=>true,'msg'=>'上传成功'], JSON_UNESCAPED_UNICODE);
        }else{
            return $this->_form($this->table, 'upload');
        }
    }

   private function getExt($filename)
    {
        $arr = explode('.',$filename);
        return array_pop($arr);;
    }


    private function ReadCsv($uploadfile='')
    {
        $file = fopen($uploadfile, "r");
        while (!feof($file)) {
            $data[] = fgetcsv($file);
        }
        $data = eval('return ' . iconv('gbk', 'utf-8', var_export($data, true)) . ';');
        foreach ($data as $key => $value) {
            if (!$value) {
                unset($data[$key]);
            }
        }
        fclose($file);
        return array_map('reset',$data);
    }

}